﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EngineOfEvermore.Common;
using GorgonLibrary.Graphics;
using GorgonLibrary;
using EngineOfEvermore.Scene.Visual;
using System.Drawing;

namespace EngineOfEvermore.Scene.Physics
{
    public class PhysicsDebugRenderingComponent : SceneObjectComponent
    {
        class InternalDrawable : Drawable
        {
            public CollisionComponent CollisionComponent;
            public SensorComponent SensorComponent;

            public override void Draw( RectangleF visibleArea, FrameEventArgs e )
            {
                Gorgon.Screen.BeginDrawing();

                if ( this.CollisionComponent != null )
                {
                    foreach ( CollisionShape shape in CollisionComponent.Shapes )
                    {
                        switch ( shape.ShapeType )
                        {
                            case CollisionShapeType.Circle:
                                _drawCircle( shape, System.Drawing.Color.Green );
                                break;

                            case CollisionShapeType.Rectangle:
                                _drawRectangle( shape, System.Drawing.Color.Green );
                                break;

                            case CollisionShapeType.RoundedRectangle:
                                _drawRoundedRectangle( shape, System.Drawing.Color.Green );
                                break;

                            case CollisionShapeType.Polygon:
                                _drawPolygon( shape, System.Drawing.Color.Green );
                                break;
                        }
                    }

                    foreach ( var contact in this.CollisionComponent.Contacts )
                    {
                        Gorgon.Screen.Circle( contact.Position.X, contact.Position.Y, 5, 
                            System.Drawing.Color.Red );
                    }
                }

                if ( this.SensorComponent != null )
                {
                    foreach ( CollisionShape shape in 
                        SensorComponent.Sensors.Select( x => x.Shape ) )
                    {
                        switch ( shape.ShapeType )
                        {
                            case CollisionShapeType.Circle:
                                _drawCircle( shape, System.Drawing.Color.Red );
                                break;

                            case CollisionShapeType.Rectangle:
                                _drawRectangle( shape, System.Drawing.Color.Red );
                                break;

                            case CollisionShapeType.RoundedRectangle:
                                _drawRoundedRectangle( shape, System.Drawing.Color.Red );
                                break;

                            case CollisionShapeType.Polygon:
                                _drawPolygon( shape, System.Drawing.Color.Red );
                                break;
                        }
                    }
                }

                Gorgon.Screen.EndDrawing();
            }

            void _drawCircle( CollisionShape shape, System.Drawing.Color color )
            {
                CircleShape circle = (CircleShape) shape;

                Vector2d position = CollisionComponent.Owner.Position + circle.Offset;
                Gorgon.Screen.Circle( position.X, position.Y, circle.Radius, color );
            }

            void _drawRectangle( CollisionShape shape, System.Drawing.Color color )
            {
                RectangleShape rect = (RectangleShape) shape;

                Gorgon.Screen.Rectangle(
                    rect.Rectangle.X + CollisionComponent.Owner.Position.X,
                    rect.Rectangle.Y + CollisionComponent.Owner.Position.Y,
                    rect.Rectangle.Width,
                    rect.Rectangle.Height,
                    color
                    );
            }

            void _drawRoundedRectangle( CollisionShape shape, System.Drawing.Color color )
            {
                RoundedRectangleShape rectShape = (RoundedRectangleShape) shape;

                RectangleF rect = rectShape.Rectangle;
                rect.X += CollisionComponent.Owner.Position.X;
                rect.Y += CollisionComponent.Owner.Position.Y;
                
                float radius = rectShape.CornerRadius;

                float v0X = rect.Left + radius;
                float v0Y = rect.Top;

                float v1X = rect.Right - radius;
                float v1Y = rect.Top;

                float v2X = rect.Right;
                float v2Y = rect.Top + radius;

                float v3X = rect.Right;
                float v3Y = rect.Bottom - radius;

                float v4X = rect.Right - radius;
                float v4Y = rect.Bottom;

                float v5X = rect.Left + radius;
                float v5Y = rect.Bottom;

                float v6X = rect.Left;
                float v6Y = rect.Bottom - radius;

                float v7X = rect.Left;
                float v7Y = rect.Top + radius;

                Gorgon.Screen.Line( v0X, v0Y, v1X - v0X, v1Y - v0Y, color );
                Gorgon.Screen.Line( v1X, v1Y, v2X - v1X, v2Y - v1Y, color );
                Gorgon.Screen.Line( v2X, v2Y, v3X - v2X, v3Y - v2Y, color );
                Gorgon.Screen.Line( v3X, v3Y, v4X - v3X, v4Y - v3Y, color );
                Gorgon.Screen.Line( v4X, v4Y, v5X - v4X, v5Y - v4Y, color );
                Gorgon.Screen.Line( v5X, v5Y, v6X - v5X, v6Y - v5Y, color );
                Gorgon.Screen.Line( v6X, v6Y, v7X - v6X, v7Y - v6Y, color );
                Gorgon.Screen.Line( v7X, v7Y, v0X - v7X, v0Y - v7Y, color );

                Gorgon.Screen.Circle(
                    rect.Left + radius,
                    rect.Top + radius,
                    radius,
                    color
                    );

                Gorgon.Screen.Circle(
                    rect.Right - radius,
                    rect.Top + radius,
                    radius,
                    color
                    );

                Gorgon.Screen.Circle(
                    rect.Right - radius,
                    rect.Bottom - radius,
                    radius,
                    color
                    );

                Gorgon.Screen.Circle(
                    rect.Left + radius,
                    rect.Bottom - radius,
                    radius,
                    color
                    );
            }

            void _drawPolygon( CollisionShape shape, System.Drawing.Color color )
            {
                Vector2d scoPos = CollisionComponent.Owner.Position;
                IEnumerable<Vector2d> vertices = ( (PolygonShape) shape ).Vertices;

                Vector2d? first = null;
                Vector2d? prev = null;

                foreach ( Vector2d vertex in vertices )
                {
                    if ( first.HasValue )
                    {
                        float x0 = scoPos.X + prev.Value.X;
                        float y0 = scoPos.Y + prev.Value.Y;

                        float w = ( scoPos.X + vertex.X ) - x0;
                        float h = ( scoPos.Y + vertex.Y ) - y0;

                        Gorgon.Screen.Line( x0, y0, w, h, color );
                    }
                    else
                    {
                        first = vertex;
                    }

                    prev = vertex;
                }

                if ( first.HasValue && prev.HasValue )
                {
                    float x0 = scoPos.X + prev.Value.X;
                    float y0 = scoPos.Y + prev.Value.Y;

                    float w = ( scoPos.X + first.Value.X ) - x0;
                    float h = ( scoPos.Y + first.Value.Y ) - y0;

                    Gorgon.Screen.Line( x0, y0, w, h, color );
                }
            }
        }

        InternalDrawable _drawable = new InternalDrawable();

        internal protected override void OnSiblingAdded( SceneObjectComponent sibling )
        {
            base.OnSiblingAdded( sibling );

            if ( sibling is CollisionComponent )
            {
                _drawable.CollisionComponent = (CollisionComponent) sibling;
            }
            else if ( sibling is SensorComponent )
            {
                _drawable.SensorComponent = (SensorComponent) sibling;
            }

            if ( Scene != null && 
                ( _drawable.CollisionComponent != null || _drawable.SensorComponent != null ) )
            {
                VisualSubSystem vss = Scene.GetSubSystem<VisualSubSystem>();

                if ( !vss.IsDrawableRegistered( _drawable ) )
                {
                    vss.RegisterDrawable( _drawable );
                }
            }
        }

        internal protected override void OnSiblingRemoved( SceneObjectComponent sibling )
        {
            if ( sibling is CollisionComponent )
            {
                _drawable.CollisionComponent = null;
            }
            else if ( sibling is SensorComponent )
            {
                _drawable.SensorComponent = null;
            }

            if ( Scene != null && _drawable.CollisionComponent == null && 
                _drawable.SensorComponent == null )
            {
                VisualSubSystem vss = Scene.GetSubSystem<VisualSubSystem>();

                if ( vss.IsDrawableRegistered( _drawable ) )
                {
                    vss.UnregisterDrawable( _drawable );
                }
            }

            base.OnSiblingRemoved( sibling );
        }

        internal protected override void OnAddToScene( SceneGraph scene )
        {
            base.OnAddToScene( scene );

            if ( _drawable.CollisionComponent != null )
            {
                scene.GetSubSystem<VisualSubSystem>().
                        RegisterDrawable( _drawable );
            }
        }

        internal protected override void OnRemoveFromScene( SceneGraph scene )
        {
            if ( _drawable.CollisionComponent != null )
            {
                scene.GetSubSystem<VisualSubSystem>().
                        UnregisterDrawable( _drawable );
            }

            base.OnRemoveFromScene( scene );
        }
    }
}
